package com.classroommanagesystem.utils;

/**
 * @author victory
 * @date 2025/10/25 17:24
 */

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.classroommanagesystem.exception.BusinessException;

import java.util.Date;
import java.util.Map;

public class JwtUtil {
    private static final String KEY = "example"; // 密钥 可任意

    // 接收业务数据，生成token
    public static String genToken(Map<String, Object> claims) {
        return JWT.create()
                .withClaim("claims", claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24))  // 过期时间 24小时
                .sign(Algorithm.HMAC256(KEY));
    }

    // 接收token，验证token，返回业务数据
    public static Map<String, Object> parseToken(String token) {
        return JWT.require(Algorithm.HMAC256(KEY))
                .build()
                .verify(token)
                .getClaim("claims")
                .asMap();
    }

    // 从token中提取用户ID
    public static Long getUserId(String token) {
        Map<String, Object> map = parseToken(token);
        Object id = map.get("id");
        if (!(id instanceof Number)) {
            throw new BusinessException("Token中用户ID格式错误");
        }
        return ((Number) id).longValue();
    }


}
